<template>
  <div class="app-container">
    <div class="content">
      <div class="head">
        <el-form inline :model="queryParams">
          <el-form-item label="流程名称">
            <el-input v-model.trim="queryParams.name" placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="标识Key">
            <el-input v-model.trim="queryParams.key" placeholder="请输入标识Key" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="queryData">查询</el-button>
            <el-button @click="reload">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="body">
        <el-alert
          style="margin: 10px 0;"
          title="说明：当有多个相同标识Key的流程时，只显示其最新版本流程。"
          type="info"
          show-icon
          :closable="false"
        />
        <el-table
          :loading="loading"
          :data="list"
          stripe
          border
          style="width: 100%;"
        >
          <el-table-column
            align="center"
            type="index"
            label="序号"
            width="50"
          />
          <el-table-column
            align="center"
            prop="name"
            label="流程名称"
            min-width="160"
          />
          <el-table-column
            align="center"
            prop="key"
            label="标识Key"
            min-width="120"
          />
          <el-table-column
            align="center"
            prop="state"
            label="状态"
            width="90"
          >
            <template #default="{row}">
              <!-- 流程定义状态，已启动、已暂停 -->
              <el-tag :type="row.state == '已启动' ? 'success': 'danger'">{{ row.state }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="xmlName"
            label="流程XML"
            width="240"
          >
            <template #default="{row}">
              <el-link type="primary" @click="clickExportXML(row)">{{ row.xmlName }}</el-link>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="pngName"
            label="流程图片"
            min-width="240"
          >
            <template #default="{row}">
              <el-link type="primary" @click="clickPreviewImg(row)">{{ row.pngName }}</el-link>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="version"
            label="版本号"
            width="90"
          >
            <template #default="{row}"> v{{ row.version }}.0</template>
          </el-table-column>
      
          <el-table-column
            align="center"
            prop="deploymentTime"
            label="部署日期"
            width="180"
          />
          <el-table-column
            align="center"
            label="操作"
            fixed="right"
            width="230"
          >
            <template #default="{row}">
              <el-button v-if="row.state == '已启动'" type="warning" @click="updateState(row)">暂停</el-button>
              <el-button v-else type="primary" @click="updateState(row)">启动</el-button>
              <el-button @click="clickDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-dialog
          ref="imgRef"
          v-model="open2"
          align="center"
          width="70%"
          title="流程图展示"
        >
          <el-image :src="url">
            <!-- <div>流程图加载中 <i class="el-icon-loading"></i></div> -->
          </el-image>
        </el-dialog>
      </div>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { ref, getCurrentInstance } from 'vue'
import { ElButton, ElMessageBox, ElMessage } from 'element-plus'
import { processList, putProcess, delProcess, getProcess, getProcessimg } from '@/api/workflow/index'

const queryParams = ref({ 
  name: '',
  key: '',
  pageSize: 10,
  pageNum: 1 })
const { proxy } = getCurrentInstance() as any
const queryData = () => {
  getList()  
}
// const {
//   appContext: {
//     config: {
//       globalProperties: { $download },
//     },
//   },
// } = getCurrentInstance()
const open2 = ref(false)
const loading = ref(false)
const reload = () => {
  proxy.queryParams = {}
  getList()
}
const list = ref(null)
// 
const updateState = (row: { [key: string]: any }) => {
  // console.log(row)
  const id = JSON.parse(JSON.stringify(row.id))
  const name = row.name
  const state = row.state
  if (state == '已启动') {
    ElMessageBox.confirm(`暂停后，此流程下的所有任务都不允许往后流转，您确定暂停【"${ name || row.key }"}】吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => putProcess({ id })).then((res => {
      if (res.code == 200) {
        getList()
        ElMessage.success('操作成功')
      }
    }))
  } else {
    ElMessageBox.confirm(`启动后，此流程下的所有任务都允许往后流转，您确定启动【"${ name || row.key }"}】吗?`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => putProcess({ id })).then((res => {
      if (res.code == 200) {
        getList()
        ElMessage.success('操作成功')
      }
    }))
  }
}
 
const clickDelete = (row: { [key: string]: any }) => {
  const name = row.name
  const id = row.deploymentId
  ElMessageBox.confirm(`您确定删除【"${ name }"}】吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => delProcess(id)).then((res => {
    if (res.code == 200) {
      getList()
      ElMessage.success('删除成功')
    }
  }))
}
const clickExportXML = async (row: { [key: string]: any }) => {
  const id = JSON.parse(JSON.stringify(row.id))
  const type = 'xml'
  // window.open(getProcess(id, type))
  window.open(`${ import.meta.env.VITE_BASE_API }/activiti/process?id=${ id }&type=${ type }`)
  // $download(getProcess(id, type), `流程模型_${ new Date().getTime() }.xml`)
  // getProcess(id, type).then(res => {
  //   console.log(res)
  // })
}
// 下载图片
const url = ref(null)

const clickPreviewImg = (row: { [key: string]: any }) => {
  const id = JSON.parse(JSON.stringify(row.id))
  const type = 'png'
 
  open2.value = true

  getProcessimg(id, type).then(res => {
    const blob = new Blob([res]) // 返回的文件流数据
    // const imageUrl = URL.createObjectURL(blob) // 将他转化为路径
    const imageUrl = window.URL.createObjectURL(blob)
    console.log(res, imageUrl)
      
    proxy.url = imageUrl
  })
  // getProcessimg(id, type).then(({ data }) => {
  //   const blob = new Blob([data])
  //   const urls = window.URL.createObjectURL(blob) 
  //   proxy.url = urls
  // })
}
const getList = () => {
  processList(queryParams.value).then(res => {
    try {
      loading.value = true
      if (res.code == 200) {
        list.value = res.data
      } else {
        ElMessage.error(res.msg)
      }
    } catch (error) {
      console.log(error)
    } finally {
      // loading.value = false
    }
  })
}
getList()
</script>
<style lang="less" scoped>
.app-container {
  padding: 20px;
  .content {
    .head {
      border-radius: 10px;
      padding: 20px;
      background: #fff;
      margin-bottom: 20px;
    }
    .body {
      border-radius: 10px;
      padding: 20px;
      background: #fff;
    }
  }
}
</style>